package com.whale.mq.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.whale.entity.Orders;
import com.whale.mq.service.ConsumeService;
import com.whale.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 3y
 */
@Service
public class ConsumeServiceImpl implements ConsumeService {

    @Autowired
    private  ObjectMapper objectMapper;
    @Autowired
    private OrderService orderService;
    /**
     * Kafka消费逻辑
     * @param JsonValue 接收到的JSON格式的字符串消息
     */
    @Override
    public void consumerKafka(String JsonValue) {
        try {
            // 使用Jackson库将JSON字符串反序列化为Order对象
            Orders order = objectMapper.readValue(JsonValue, Orders.class);

            // 调用业务服务校验库存并下单
            boolean isOrderProcessed = orderService.processOrder(order);

            if (isOrderProcessed) {
                // 如果下单成功，可以进行其他业务逻辑，比如记录日志或更新状态
                System.out.println("Order processed successfully for OrderId: " + order.getId());
            } else {
                // 如果下单失败，可以进行错误处理，比如重试或记录错误
                System.out.println("Order processing failed for OrderId: " + order.getId());
            }
        } catch (Exception e) {
            // 处理异常，比如记录日志
            System.err.println("Error processing Kafka message: " + e.getMessage());
        }
    }

    /**
     * rabbit消费逻辑
     * @param outTradeNo 接收到的JSON格式的字符串消息
     */
    @Override
    public void consumerRabbit(String outTradeNo) {
        orderService.paySuccess(outTradeNo);
    }
}
